<?php


namespace App\Http\Requests;

use App\Exceptions\AdminException;
use App\Exceptions\ApiException;
use Illuminate\Foundation\Http\FormRequest;

class BaseRequest extends FormRequest
{

    protected $action = "";

    protected $rules = [];

    protected $messages = [];


    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {

        return [

        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return data_get($this->rules, $this->action, []);
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return data_get($this->messages, $this->action, []);
    }


    /**
     * Prepare the data for validation.
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        if (empty($this->route())) return;
        $route = $this->route()->action;
        if (isset($route['controller'])) {
            $action = explode('@', $route['controller']);
            if (isset($action[1])) {
                $this->action = lcfirst($action[1]);
            }
            //
        }
        $data = $this->convert($this->all());
        $this->merge($data);
    }


    /**
     * Handle a failed validation attempt.
     *
     * @param \Illuminate\Contracts\Validation\Validator $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        $message = [];
        foreach ($validator->getMessageBag()->toArray() as $val) {
            foreach ($val as $v) {
                $message[] = $v;
            }
        }
        if ($message) {
            if (defined('MODULE_NAME') && MODULE_NAME == 'api') {
                throw new ApiException(join(";", $message));
            }
            if (defined('MODULE_NAME') && MODULE_NAME == 'admin') {
                throw new AdminException(join(";", $message));
            }
            parent::failedValidation($validator);
        }
    }

    /**
     * Handle a passed validation attempt.
     *
     * @return void
     */
    protected function passedValidation()
    {
        //
    }


    protected function convert($data) {
        if (!is_array($data)) return $data;

        $result= [];

        foreach ($data as $k=> $value) {
            if(!empty($val) && is_string($val)){
                $val = trim($val);
            }
            $value = is_string($value) ?  trim($value) : $value;
            $result[\Str::snake($k)] = is_array($value) ? $this->convert($value) : $value;
        }


        return $result;
    }

}
